package com.sca.deal.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.sca.deal.product.dao"}, sqlSessionFactoryRef = "productSqlSessionFactory")
public class MybatisProductConf {

    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    @Autowired
    @Qualifier("productDataSource")
    private DataSource productDataSource;

    @Bean
    @Primary
    public SqlSessionFactory productSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(productDataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/product/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    @Primary
    public SqlSessionTemplate productSqlSessionTemplate() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(productSqlSessionFactory());
        return template;
    }

}
